import { RootThunkAction } from "@/types/store";
import { http } from "@/utils/http";
import { clearToken, setToken } from "@/utils/token";
import type { Token } from "@/types/data";
import type { LoginResponse } from "@/types/data";
// 登录数据类型
type loginParams = {
  mobile: string;
  code: string;
};

export const login = (values: loginParams): RootThunkAction => {
  return async (dispatch) => {
    // 发送请求
    const res = await http.post<LoginResponse>("/authorizations", values);
    // 获取token
    const tokens = res.data.data;
    // 设置本地token
    setToken(tokens);
    // 分发actions将token存入redux state 中
    dispatch({ type: "login/token", payload: tokens });
  };
};

export const getCode = (mobile: string) => {
  return async () => {
    await http.get(`/sms/codes/${mobile}`);
  };
};
// 退出登录
export const logout = (): RootThunkAction => {
  return async (dispatch) => {
    dispatch({ type: "login/logout" });
    clearToken();
  };
};
